package com.sleep.ws.server;

import com.sleep.ws.server.utils.DateTimeUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;

public class ChannelGroupPlus {
    /**
     * 通道集合
     */
    private ChannelGroup channels;

    /**
     * 创建topic时间
     */
    private long createTime;

    /**
     * 最后推送时间
     */
    private long lastTimeStamp;

    /**
     * 计数器
     */
    private  final LongAdder count = new LongAdder();

    /**
     * 生产者集合
     */
    private final Map<String, Long> products = new HashMap<>();

    public ChannelGroupPlus(ChannelGroup channels) {
        this.channels = channels;
        this.createTime = System.currentTimeMillis();
    }

    public ChannelGroup getChannels() {
        return channels;
    }

    public void setChannels(ChannelGroup channels) {
        this.channels = channels;
    }

    public long getLastTimeStamp() {
        return lastTimeStamp;
    }

    public void upLastTimeStamp() {
        this.lastTimeStamp = System.currentTimeMillis();
    }

    public long getCount() {
        return count.longValue();
    }

    public void addCount(){
        count.add(1);
    }

    public long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
    }

    public LinkedList<Map> getProducts() {
        LinkedList<Map> list = new LinkedList<>();
        products.keySet().forEach(i->{
            HashMap<String, Object> map = new HashMap<>();
            map.put("address",i);
            map.put("lastTime", DateTimeUtil.timestampToString(products.get(i)));
            list.add(map);
        });
        return list;
    }

    public void addProduct(Channel channel) {
        InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
        String ip = insocket.getAddress().getHostAddress();
        int port = insocket.getPort();
        products.put(ip+port,System.currentTimeMillis());
    }
}
